/*
Copyright (c) 2012 the VATSIM Connector project

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "connection.h"
#include "libvatconn.h"
#include "xsbnet/PCSBSocket.h"
#include "xsbnet/PCSBSocketUDP.h"
#include "md5/md5.h"
#include <cstring>

class VconConnectionImpl : public VconConnection
{
public:
  VconConnectionImpl() : m_sock(0), m_localPort(0), m_remotePort(0), m_remoteAddr(0)
  { PCSBSocket::StartupNetworking(true); }

  virtual ~VconConnectionImpl()
  { disable(); PCSBSocket::ShutdownNetworking(false); }

  void setPorts(int local, int remote) { m_localPort = local; m_remotePort = remote; }
  void setRemoteHost(char const* addr) { m_remoteAddr = PCSBSocket::LookupAddress(addr); }
  void setUserPass(char const* user, char const* pass);
  char const* enable();
  void disable();
  void pollReceivedMessages();
  void sendQueuedMessages();

private:
  void sendMessage(QueuedMsg const&);
  void receiveMessage(unsigned char*, size_t len);

  PCSBSocketUDP* m_sock;
  unsigned short m_localPort, m_remotePort;
  unsigned long m_remoteAddr;
  std::string m_identifier;
};

VconConnection* VconConnection::create()
{
  return new VconConnectionImpl;
}

void VconConnectionImpl::setUserPass(char const* user, char const* pass)
{
  std::string hash;
  md5_state_t state;
  md5_byte_t digest[16];

  md5_init(&state);
  md5_append(&state, reinterpret_cast<md5_byte_t const*>(pass), std::strlen(pass));
  md5_finish(&state, digest);

  hash = user;
  hash += md5_tostring(digest);

  md5_init(&state);
  md5_append(&state, reinterpret_cast<md5_byte_t const*>(hash.c_str()), hash.size());
  md5_finish(&state, digest);

  m_identifier = md5_tostring(digest);
}

char const* VconConnectionImpl::enable()
{
  if (! (m_localPort && m_remotePort && m_remoteAddr))
    return "UDP port number or connector IP address not initialized";

  if (m_identifier.empty())
    return "Username or password not initialized";

  assert(m_handlerPP && m_handlerWX && m_handlerMG && m_handlerSQ);

  if (m_sock) disable();
  try {
    m_sock = new PCSBSocketUDP (m_localPort);
  }
  catch(...) {
    return "Failed to establish UDP socket";
  }
  return 0;
}

void VconConnectionImpl::disable()
{
  if (m_sock) delete m_sock;
  m_sock = 0;
}

void VconConnectionImpl::pollReceivedMessages()
{
  if (m_sock)
  {
    unsigned char buf[vconMaxMsgSize];
    unsigned long addr;
    unsigned short port;
    long len;

    while (true)
    {
      len = m_sock->ReadData(buf, vconMaxMsgSize, &addr, &port);
      if (len <= 0) return;

      receiveMessage(buf, len);
    }
  }
}

void VconConnectionImpl::receiveMessage(unsigned char* buf, size_t len)
{
  static size_t const offset = 3;

  if (len < offset)
  {
    // warn about incomplete message?
    return;
  }

  int type = VCON_MSG_TYPE_NUM(buf[0], buf[1], buf[2]);

  bool ok = handleMessage(type,
    reinterpret_cast<char*>(buf) + offset, len - offset);

  if (! ok)
  {
    // warn about malformed message?
  }
}

void VconConnectionImpl::sendQueuedMessages()
{
  if (m_sock)
  {
    while (! m_queue.empty())
    {
      sendMessage(m_queue.front());
      m_queue.pop_front();
    }
  }
  else m_queue.clear();
}

inline void VconConnectionImpl::sendMessage(QueuedMsg const& msg)
{
  std::string str = msg.id;
  str += ":";
  str += m_identifier;
  str += msg.msg;
  str += "\r\n";

  void* buf = static_cast<void*>(const_cast<char*>(str.c_str()));

  size_t len = m_sock->WriteData(buf, str.size(), m_remoteAddr, m_remotePort);

  if (len != str.size())
  {
    // warn about failure to send message?
  }
}